package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"novel/cache"
	"novel/models"
	"os"
	"path/filepath"
	"time"
)

type NovelController struct {
	beego.Controller
}

func (c *NovelController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	i := (page - 1) * size

	//key := fmt.Sprintf("novel_list")
	//countData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	var novels []models.Novel
	//if countData != "" {
	//	json.Unmarshal([]byte(countData), &novels)
	//} else {
	models.DB.Model(&models.Novel{}).Offset(i).Limit(size).Find(&novels).
		Select("novels.*, novel_type_ids.name").
		Joins(" join novel_type_ids on novels.type_id = novel_type_ids.id").Scan(&novels)
	//	jsondata, _ := json.Marshal(novels)
	//	cache.Rdb.Set(cache.Ctx, key, jsondata, time.Minute*1)
	//}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "展示成功",
		"data": novels,
	}
	c.ServeJSON()
	return
}
func (c *NovelController) Upload() {
	file, m, err := c.GetFile("image")
	if err != nil {
		return
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpeg" && ext != ".png" && ext != ".jpg" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "图片上传不能上传.jpeg,.png.jpg ",
		}
		c.ServeJSON()
		return
	}
	if m.Size >= 2*1024*1024 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "图片上传不能大于2mb ",
		}
		c.ServeJSON()
		return
	}
	OpenFile, err := os.OpenFile("static/img/"+m.Filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
	if err != nil {
		return
	}
	io.Copy(OpenFile, file)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "上传成功",
		"data": "http://127.0.0.1:8080/static/img/" + m.Filename,
	}
	c.ServeJSON()
	return

}
func (c *NovelController) Add() {
	var err error
	title := c.GetString("title")
	typeId, _ := c.GetInt("type_id")
	num, _ := c.GetInt("num")
	connect := c.GetString("connect")
	image := c.GetString("image")

	if title == "" || typeId == 0 || num == 0 || connect == "" || image == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "添加不能为空",
		}
		c.ServeJSON()
		return
	}
	novels := models.Novel{
		Title:   title,
		TypeId:  typeId,
		Num:     num,
		Connect: connect,
		Image:   image,
	}
	key := fmt.Sprintf("novel_ID_%d", novels.ID)
	jsondata, _ := json.Marshal(novels)
	cache.Rdb.Set(cache.Ctx, key, jsondata, time.Minute*1)
	if err = novels.Add(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "系统错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "添加成功",
	}
	c.ServeJSON()
	return
}
